//
//  XYOAuthViewController.swift
//  01-新浪微博
//
//  Created by 陈许亚 on 16/3/8.
//  Copyright © 2016年 cxy. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class XYOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置导航栏
        setUpNavBar()
        
        //加载授权页
        loadOAuthPage()
        
        
        
    }
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.whiteColor()
        webView.delegate = self
    }
    
    //view将要消失的时候将加载进度停止
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(true)
        
        SVProgressHUD.dismiss()
    }
    
    
//    override func viewWillAppear(animated: Bool) {
//        loadView()
//    }
    
    //设置导航栏的左右按钮
    func setUpNavBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "accountNumberForTest")
        
        
    }
    
    //点击关闭按钮
    func close(){
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    //测试账号密码
    func accountNumberForTest(){
        //需要在webView中 设置账号和密码,获取javascrip代码
        let jsString = "document.getElementById('userId').value = 'cxyvips@126.com', document.getElementById('passwd').value = 'cxyxingyunm@'"
        
        //通过字符串来执行javascrip 代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)

        
    }
    
    //加载授权页，请求加载授权页
    func loadOAuthPage(){
        // https://api.weibo.com/oauth2/authorize?client_id=2255699244&redirect_uri=http://www.baidu.com
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        //网页加载请求
        webView.loadRequest(request)
        
    }
}

//webView的协议方法
extension XYOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //一般协议方法，返回值类型是bool类型，默认返回yes,相对应的控件就能正常工作，反之不能
    //在这个方法中可以监测webView每次加载新的页面发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request.URL)
        //判断网络请求的url字符创是否存在，
        guard let urlString = request.URL?.absoluteString else {
            
            return false
        }
//        print("urlString=",urlString)
        //存在的话判断字符串中是否包含“code”字符串
        if urlString.containsString("code") {
        
        guard let query = request.URL?.query else {
            
            return false
        }
//        print("query=",query)
        
        let codeStr = "code="
        //将字符串转化为NSString 
        let code = (query as NSString).substringFromIndex(codeStr.characters.count)
//        print("code=",code)
        //使用code来获取token
            XYUserAccount.sharedAccount.loadAccessToken(code, finished: { (isSuccessed) -> () in
                if !isSuccessed {
                    SVProgressHUD.showErrorWithStatus("网络君获取失败")
                    return
                }
                //登录成功
                //调用导航栏的关闭按钮来退出当前控制器
                self.close()
                //退出授权页面之后，进入到欢迎首页
                UIApplication.sharedApplication().keyWindow?.rootViewController = XYWelcomeViewController()
                
                
            })
            return false
            
        }
        
        return  true
    }
}


